package junmo.s3caesar.mandu.nhkradionews.activity;

import junmo.s3caesar.mandu.nhkradionews.R;
import junmo.s3caesar.mandu.nhkradionews.service.INewsPlayerService;
import junmo.s3caesar.mandu.nhkradionews.service.NewsPlayerService;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class NewsPlayerActivity extends Activity implements OnClickListener, OnSeekBarChangeListener {
	
	private static final String CLASSTAG = NewsPlayerActivity.class.getSimpleName();
	
	private final String DICTIONARY_URL = "http://m.jpdic.naver.com/";
	private final int NOTIFICATION_ID = R.string.news_player_notification_id;

	private String enclosureUrl;
	private int duration = NewsPlayerService.PROGRESS_START;
	
	private TextView title;
	
	private SeekBar seekBar;
	private DisplaySeekBarProgress displaySeekBarProgress;
	private boolean isDisplaySeekBar = true;
	private int progress = NewsPlayerService.PROGRESS_START;
	
	private TextView elapsedTime;
	private TextView fullTime;

	private Button playButton;
	private Button pauseButton;
	private Button restartButton;
	private Button stopButton;

	private Button goBackButton;
	private Button goForwardButton;
	private Button reloadButton;
	private Button windowButton;

	private WebView webView;
	
	private NotificationManager notificationManager;
	private Notification notification;
	
	private boolean isBackPressed = false;
	
	private INewsPlayerService service;
	private boolean bound;
	
	private class DisplaySeekBarProgress extends AsyncTask<Void, Void, Void> {
		@Override
		protected Void doInBackground(Void... params) {
			Log.v(CLASSTAG, "DisplaySeekBarProgress:doInBackground()");
			
			int current = 0;
			while(isDisplaySeekBar) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				if(bound) {
					try {
						current = service.getCurrentPosition();
						if(service.isPlaying()) {
							seekBar.setProgress(current);
						}
					} catch (RemoteException e) {
						e.printStackTrace();
					}
				}
			}
			Log.v(CLASSTAG, "DisplaySeekBarProgress:doInBackground() - finish");
			return null;
		}
	}
	
	// media player connection
	private ServiceConnection connection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName name, IBinder iservice) {
			Log.v(CLASSTAG, "ServiceConnection:onServiceConnected()");
			service = INewsPlayerService.Stub.asInterface(iservice);
			bound = true;
			try {
				duration = service.init(enclosureUrl);
				seekBar.setMax(duration);
				settingFullTime(duration);
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			Log.v(CLASSTAG, "ServiceConnection:onServiceDisconnected()");
			service = null;
			bound = false;
		};
		
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Log.v(CLASSTAG, "onCreate()");
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.news_player_activity);
		
		enclosureUrl = getIntent().getStringExtra("enclosureUrl");
		
		title = (TextView) findViewById(R.id.title_id);
		title.setText(getIntent().getStringExtra("title"));
		title.setSelected(true);	

		seekBar = (SeekBar) findViewById(R.id.seek_bar_id);
		seekBar.setVisibility(ProgressBar.VISIBLE);
		seekBar.setProgress(NewsPlayerService.PROGRESS_START);
		seekBar.setOnSeekBarChangeListener(this);
		displaySeekBarProgress = new DisplaySeekBarProgress();
		
		elapsedTime = (TextView) findViewById(R.id.elapsed_time_id);
		fullTime = (TextView) findViewById(R.id.full_time_id);
		
		playButton = (Button) findViewById(R.id.play_button_id);
		playButton.setOnClickListener(this);
		pauseButton = (Button) findViewById(R.id.pause_button_id);
		pauseButton.setOnClickListener(this);
		stopButton = (Button) findViewById(R.id.stop_button_id);
		stopButton.setOnClickListener(this);
		
		// dictionary
		webView = (WebView) findViewById(R.id.web_view_id);
		setting4WebView();
		webView.loadUrl(DICTIONARY_URL);
		
		goBackButton = (Button) findViewById(R.id.go_back_button_id);
		goBackButton.setOnClickListener(this);
		if(webView.canGoBack()) {
			goBackButton.setEnabled(true);
		} else {
			goBackButton.setEnabled(false);
		}
		goForwardButton = (Button) findViewById(R.id.go_forward_button_id);
		goForwardButton.setOnClickListener(this);
		if(webView.canGoForward()) {
			goForwardButton.setEnabled(true);
		} else {
			goForwardButton.setEnabled(false);
		}
		reloadButton = (Button) findViewById(R.id.reload_button_id);
		reloadButton.setOnClickListener(this);
		windowButton = (Button) findViewById(R.id.window_button_id);
		windowButton.setOnClickListener(this);
		
		notification();
	}
	
	private void settingElapsedTime(int current) {
		int second = (current % 60000) / 1000;
		int minute = current / 60000;
		int hour = 0;
		if(minute > 59) {
			hour = minute / 60;
		}
		
		String formattedElapsedTime = String.format("%02d:%02d:%02d", hour, minute, second);
		elapsedTime.setText(formattedElapsedTime);
	}

	private void settingFullTime(int duration) {
		Log.v(CLASSTAG, "settingFullTime : [" + duration + "]");
		
		int second = (duration % 60000) / 1000;
		int minute = duration / 60000;
		int hour = 0;
		if(minute > 59) {
			hour = minute / 60;
		}

		String formattedFullTime = String.format("%02d:%02d:%02d", hour, minute, second);
		fullTime.setText(formattedFullTime);
		Log.v("formattedFullTime", formattedFullTime);
	}

	@SuppressLint("SetJavaScriptEnabled")
	private void setting4WebView() {
		Log.v(CLASSTAG, "setting4WebView()");
		WebSettings webSettings = webView.getSettings();
		webSettings.setSavePassword(false);
		webSettings.setSaveFormData(false);
		webSettings.setJavaScriptEnabled(true);
		webSettings.setSupportZoom(false);
		webView.setWebViewClient(new WebClient());
	}
	
	private class WebClient extends WebViewClient {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
        	Log.v(CLASSTAG, "WebClient:shouldOverrideUrlLoading()");
            view.loadUrl(url);
            return true;
        }
        
        @Override
        public void onPageFinished(WebView view, String url) {
        	// TODO Auto-generated method stub
        	super.onPageFinished(view, url);
        	if(view.canGoBack()) {
        		goBackButton.setEnabled(true);
        	} else {
        		goBackButton.setEnabled(false);
        	}
        	if(view.canGoForward()) {
        		goForwardButton.setEnabled(true);
        	} else {
        		goForwardButton.setEnabled(false);
        	}
        }
        
    }
	
	@Override
	protected void onStart() {
		Log.v(CLASSTAG, "onStart()");
		super.onStart();
		
		if(displaySeekBarProgress.getStatus() == AsyncTask.Status.FINISHED) {
			Log.v(CLASSTAG, "FINISHED");
		}
		if(displaySeekBarProgress.getStatus() == AsyncTask.Status.PENDING) {
			Log.v(CLASSTAG, "PENDING");
			displaySeekBarProgress.execute((Void) null);
		}
		if(displaySeekBarProgress.getStatus() == AsyncTask.Status.RUNNING) {
			Log.v(CLASSTAG, "RUNNING");
		}
		
		if(!bound) {
			this.bindService(new Intent(this, NewsPlayerService.class), connection, Context.BIND_AUTO_CREATE);
		}
	}
	
	@Override
	protected void onResume() {
		Log.v(CLASSTAG, "onResume()");
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		Log.v(CLASSTAG, "onPause()");
		super.onPause();
	}
	
	@Override
	protected void onStop() {
		Log.v(CLASSTAG, "onStop()");
		super.onStop();
		
		// 명시적으로 전화면으로 돌아가면 종료
		if(isBackPressed) {
			isDisplaySeekBar = false;
			displaySeekBarProgress.cancel(false);
			this.unbindService(connection);
			bound = false;
		}
		
//		if(!isBackPressed && mediaPlayer.isPlaying()) {
//			notificationManager.notify(NOTIFICATION_ID, notification);
//		}
	}
	
	@Override
	protected void onRestart() {
		Log.v(CLASSTAG, "onRestart()");
		super.onRestart();
		
//		notificationManager.cancel(NOTIFICATION_ID);
	}
	
	@Override
	protected void onDestroy() {
		Log.v(CLASSTAG, "onDestroy()");
		super.onDestroy();
	}
	
	/* media player control */
	
	@Override
	public void onClick(View v) {
		Log.v(CLASSTAG, "onClick()");
		switch(v.getId()) {
		case R.id.play_button_id :
			playerStart();
			break;
		case R.id.pause_button_id :
			playerPause();
			break;
		case R.id.stop_button_id :
			playerStop();
			break;
		case R.id.go_back_button_id :
			webView.goBack();
			break;
		case R.id.go_forward_button_id :
			webView.goForward();
			break;
		case R.id.reload_button_id :
			webView.reload();
			break;
		case R.id.window_button_id :
			Log.v(CLASSTAG, webView.getOriginalUrl());
			Log.v(CLASSTAG, webView.getUrl());
			
			Intent windowIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(webView.getUrl()));
			startActivity(windowIntent);
			break;
		}
	}
	
	private void playerStart() {
		Log.v(CLASSTAG, "play()");
		try {
			service.start();
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		playButton.setVisibility(View.GONE);
		pauseButton.setVisibility(View.VISIBLE);
	}
	
	private void playerPause() {
		Log.v(CLASSTAG, "pause()");
		try {
			service.pause();
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		pauseButton.setVisibility(View.GONE);
		restartButton.setVisibility(View.VISIBLE);
	}
	
	private void playerRestart() {
		Log.v(CLASSTAG, "restart()");
		try {
			service.restart();
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		restartButton.setVisibility(View.GONE);
		pauseButton.setVisibility(View.VISIBLE);
	}
	
	private void playerStop() {
		Log.v(CLASSTAG, "stop()");
		try {
			service.stop();
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		seekBar.setProgress(NewsPlayerService.PROGRESS_START);
		playButton.setVisibility(View.VISIBLE);
		pauseButton.setVisibility(View.GONE);
		restartButton.setVisibility(View.GONE);
	}
	
	/* seek bar event */
	
	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {
		this.progress = progress;
		seekBar.setProgress(progress);
		settingElapsedTime(progress);
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		Log.v(CLASSTAG, "onStartTrackingTouch()");
		try {
			if(service.isPlaying()) {
				service.pause();
			}
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		Log.v(CLASSTAG, "onStopTrackingTouch()");
		try {
			service.seekTo(this.progress);
			service.start();
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}
	
	/* 뒤로가기 event */
	
	@Override
	public void onBackPressed() {
		Log.v(CLASSTAG, "onBackPressed()");
		super.onBackPressed();
		isBackPressed = true;
	}

	/* TODO notification */
	
	private void notification() {
		// Notification
		String ns = Context.NOTIFICATION_SERVICE;
		notificationManager = (NotificationManager) getSystemService(ns);
		
		int icon = R.drawable.ic_launcher;
		CharSequence tickerText = "now playing...";
		long when = System.currentTimeMillis();
		notification = new Notification(icon, tickerText, when);
		
		Context context = getApplicationContext();
		CharSequence contentTitle = "NHKラジオニュース";
		CharSequence contentText = "now playing...";
		Intent notificationIntent = new Intent(this, NewsPlayerActivity.class);
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
		notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
//		notification.flags = Notification.FLAG_AUTO_CANCEL;
	}
	
	/* TODO menu */
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
